package br.edu.ufersa.scrumgame.mbean;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import br.edu.ufersa.scrumgame.facade.JogadorFacade;
import br.edu.ufersa.scrumgame.facade.NivelFacade;
import br.edu.ufersa.scrumgame.facade.PapelFacade;
import br.edu.ufersa.scrumgame.facade.SprintBacklogFacade;
import br.edu.ufersa.scrumgame.modelo.Jogador;
import br.edu.ufersa.scrumgame.modelo.Nivel;
import br.edu.ufersa.scrumgame.modelo.Papel;
import br.edu.ufersa.scrumgame.modelo.SprintBacklog;

@ManagedBean
@SessionScoped
public class SprintBacklogMBean {

	@EJB
	private SprintBacklogFacade sprintBacklogFacade;
	
	@EJB
	private JogadorFacade jogadorFacade;
	
	@EJB
	private NivelFacade nivelFacade;
	
	@EJB
	private PapelFacade papelFacade;
	
	private Jogador logado;
	
	private SprintBacklog sprintBacklog = new SprintBacklog();
	
	private List<SprintBacklog> itens;
	
	private List<SprintBacklog> itensFiltro;
	
	private String acao;
	
	public List<SprintBacklog> getItensFiltro() {
		return itensFiltro;
	}

	public void setItensFiltro(List<SprintBacklog> itensFiltro) {
		this.itensFiltro = itensFiltro;
	}

	public SprintBacklog getSprintBacklog() {
		if( sprintBacklog == null ) {
			sprintBacklog = new SprintBacklog();
		}
		return sprintBacklog;
	}

	public void setSprintBacklog(SprintBacklog sprintBacklog) {
		this.sprintBacklog = sprintBacklog;
	}
	
	public List<SprintBacklog> getItens() {
		itens = sprintBacklogFacade.findAll();
		return itens;
	}
	
	public List<SprintBacklog> getItensConcluidos() {
		getUsuarioLogado();
		itens = sprintBacklogFacade.findConcluidoByUser(logado.getEmail());
		return itens;
	}
	
	public List<Nivel> getNiveis() {
		return nivelFacade.findAll();
	}
	
	public List<Papel> getPapeis() {
		return papelFacade.findAll();
	}

	public String getAcao() {
		return acao;
	}

	public void novo() {
		acao = "novo";
		sprintBacklog = new SprintBacklog();
	}
	
	public void salvar() {
		if(acao == "novo") {
			sprintBacklog.setId(0);
			sprintBacklogFacade.save(sprintBacklog);
		} if(acao == "editar") {
			sprintBacklogFacade.update(sprintBacklog);
		}
	}
	
	public void editar() {
		acao = "editar";
	}
	
	public void deletar() {
		sprintBacklogFacade.delete(sprintBacklog);
	}
	
	private void getUsuarioLogado() {

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null && !authentication.getPrincipal().equals("anonymousUser")) {
			logado = jogadorFacade.findUsuarioByEmail(((User) authentication.getPrincipal()).getUsername());
		}

	}


}
